//
//  RequestManager.m
//  WOQIEarjoy
//
//  Created by 孙鹏飞 on 2023/11/6.
//

#import "RequestManager.h"
#import "AFNetworking.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "NetworkCache.h"

#import "MBProgressHUD+DFHUD.h"

#ifdef DEBUG
#define PPLog(...) printf("[%s] %s [第%d行]: %s\n", __TIME__ ,__PRETTY_FUNCTION__ ,__LINE__, [[NSString stringWithFormat:__VA_ARGS__] UTF8String])
#else
#define PPLog(...)
#endif

#define NSStringFormat(format,...) [NSString stringWithFormat:format,##__VA_ARGS__]

@implementation RequestManager

static BOOL _isOpenLog;   // 是否已开启日志打印
static NSMutableArray *_allSessionTask;
static AFHTTPSessionManager *_sessionManager;

+ (void)openLog {
    _isOpenLog = YES;
}

+ (void)closeLog {
    _isOpenLog = NO;
}
+ (BOOL)isNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachable;
}
+ (BOOL)isWWANNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachableViaWWAN;
}
+ (BOOL)isWiFiNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachableViaWiFi;
}
#pragma mark - 开始监听网络
+ (void)networkStatusWithBlock:(NetworkStatus)networkStatus {
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                networkStatus ? networkStatus(NetworkStatusUnknown) : nil;
                if (_isOpenLog) PPLog(@"未知网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                networkStatus ? networkStatus(NetworkStatusNotReachable) : nil;
                if (_isOpenLog) PPLog(@"无网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                networkStatus ? networkStatus(NetworkStatusReachableViaWWAN) : nil;
                if (_isOpenLog) PPLog(@"手机自带网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                networkStatus ? networkStatus(NetworkStatusReachableViaWiFi) : nil;
                if (_isOpenLog) PPLog(@"WIFI");
                break;
        }
    }];
}
// 取消指定URL的HTTP请求
+ (void)cancelRequestWithURL:(NSString *)URL {
    if (!URL) { return; }
    @synchronized (self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([task.currentRequest.URL.absoluteString hasPrefix:URL]) {
                [task cancel];
                [[self allSessionTask] removeObject:task];
                *stop = YES;
            }
        }];
    }
}
// 取消所有HTTP请求
+ (void)cancelAllRequest {
    // 锁操作
    @synchronized(self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            [task cancel];
        }];
        [[self allSessionTask] removeAllObjects];
    }
}

#pragma mark -  GET请求无缓存
+ (NSURLSessionTask *)GET:(NSString *)URL
               parameters:(id)parameters
                    isHud:(NSString*)hud
                 isWindow:(BOOL)isWindow
                  success:(HttpRequestSuccess)success
                  failure:(HttpRequestFailed)failure
{
    return [self GET:URL parameters:parameters isHud:hud isWindow:(BOOL)isWindow responseCache:nil success:success failure:failure];
}
#pragma mark - GET请求自动缓存
+ (NSURLSessionTask *)GET:(NSString *)URL
               parameters:(id)parameters
                    isHud:(NSString*)hud
                 isWindow:(BOOL)isWindow
            responseCache:(HttpRequestCache)responseCache
                  success:(HttpRequestSuccess)success
                  failure:(HttpRequestFailed)failure
{
    if (hud.length) {
        if (isWindow) {
            [MBProgressHUD showActivityMessageInWindow:hud];
        }else{
            [MBProgressHUD showActivityMessageInView:hud];
        }
    }
    //读取缓存
    responseCache!=nil ? responseCache([NetworkCache httpCacheForURL:URL parameters:parameters]) : nil;
    ///设置请求头
    [self setValueForHTTPHeaderFieldParameters:parameters];
    NSURLSessionTask *sessionTask = [_sessionManager GET:URL parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (hud.length) {[MBProgressHUD hideHUD]; }
        if (_isOpenLog) {PPLog(@"请求的接口：%@\n请求的参数：%@\n responseObject = %@",URL,parameters,[self jsonToString:responseObject]);
        }
        [[self allSessionTask] removeObject:task];
        
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 200) {    //这里可以做tokrn失效处理
        }else{
            NSString *msg = responseObject[@"msg"];
            if (msg.length) {  [MBProgressHUD showTipMessageInWindow:msg];}
        }
        
        success ? success(responseObject) : nil;
        //对数据进行异步缓存
        responseCache!=nil ? [NetworkCache setHttpCache:responseObject URL:URL parameters:parameters] : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (_isOpenLog) {PPLog(@"请求的接口：%@\n请求的参数：%@\n error = %@",URL,parameters,error);}
        if (hud.length) {[MBProgressHUD hideHUD]; }
        [[self allSessionTask] removeObject:task];
        failure ? failure(error) : nil;
    }];
    // 添加sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    return sessionTask;
}
#pragma mark - POST请求无缓存
+ (NSURLSessionTask *)POST:(NSString *)URL
                parameters:(id)parameters
                     isHud:(NSString*)hud
                  isWindow:(BOOL)isWindow
                   success:(HttpRequestSuccess)success
                   failure:(HttpRequestFailed)failure {
    return [self POST:URL parameters:parameters isHud:hud isWindow:(BOOL)isWindow responseCache:nil success:success failure:failure];
}
#pragma mark - POST请求自动缓存
+ (__kindof NSURLSessionTask *)POST:(NSString *)URL
                         parameters:(id)parameters
                              isHud:(NSString*)hud
                           isWindow:(BOOL)isWindow
                      responseCache:(HttpRequestCache)responseCache
                            success:(HttpRequestSuccess)success
                            failure:(HttpRequestFailed)failure
{
    if (hud.length) {
        if (isWindow) {
            [MBProgressHUD showActivityMessageInWindow:hud];
        }else{
            [MBProgressHUD showActivityMessageInView:hud];
        }
    }
    //读取缓存
    responseCache!=nil ? responseCache([NetworkCache httpCacheForURL:URL parameters:parameters]) : nil;
    ///设置请求头
//    [self setValueForHTTPHeaderFieldParameters:parameters];
    NSURLSessionTask *sessionTask = [_sessionManager POST:URL parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (hud.length) {[MBProgressHUD hideHUD]; }
        if (_isOpenLog) {PPLog(@"请求的接口：%@\n请求的参数：%@\n responseObject = %@",URL,parameters,[self jsonToString:responseObject]);
        }
        [[self allSessionTask] removeObject:task];
        
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 200) {    //这里可以做tokrn失效处理
        }else{
            NSString *msg = responseObject[@"msg"];
            if (msg.length) {  [MBProgressHUD showTipMessageInWindow:msg];}
        }
        
        success ? success(responseObject) : nil;
        //对数据进行异步缓存
        responseCache!=nil ? [NetworkCache setHttpCache:responseObject URL:URL parameters:parameters] : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (_isOpenLog) {PPLog(@"请求的接口：%@\n请求的参数：%@\n error = %@",URL,parameters,error);}
        if (hud.length) {[MBProgressHUD hideHUD]; }
        [[self allSessionTask] removeObject:task];
        failure ? failure(error) : nil;
    }];
    // 添加sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    return sessionTask;
}
#pragma mark - PUT请求无缓存
+ (NSURLSessionTask *)PUT:(NSString *)URL
                parameters:(id)parameters
                     isHud:(NSString*)hud
                  isWindow:(BOOL)isWindow
                   success:(HttpRequestSuccess)success
                   failure:(HttpRequestFailed)failure {
    return [self PUT:URL parameters:parameters isHud:hud isWindow:(BOOL)isWindow responseCache:nil success:success failure:failure];
}
#pragma mark - PUT请求,自动缓存
+ (__kindof NSURLSessionTask *)PUT:(NSString *)URL
                         parameters:(id)parameters
                              isHud:(NSString*)hud
                           isWindow:(BOOL)isWindow
                      responseCache:(HttpRequestCache)responseCache
                            success:(HttpRequestSuccess)success
                            failure:(HttpRequestFailed)failure
{
    if (hud.length) {
        if (isWindow) {
            [MBProgressHUD showActivityMessageInWindow:hud];
        }else{
            [MBProgressHUD showActivityMessageInView:hud];
        }
    }
    //读取缓存
    responseCache !=nil ? responseCache([NetworkCache httpCacheForURL:URL parameters:parameters]) : nil;
    ///设置请求头
//    [self setValueForHTTPHeaderFieldParameters:parameters];
    NSURLSessionTask *sessionTask = [_sessionManager PUT:URL parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (hud.length) {[MBProgressHUD hideHUD]; }
        if (_isOpenLog) {PPLog(@"请求的接口：%@\n请求的参数：%@\n responseObject = %@",URL,parameters,[self jsonToString:responseObject]);
        }
        [[self allSessionTask] removeObject:task];
        
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 200) {    //这里可以做tokrn失效处理
        }else{
            NSString *msg = responseObject[@"msg"];
            if (msg.length) {  [MBProgressHUD showTipMessageInWindow:msg];}
        }
        
        success ? success(responseObject) : nil;
        //对数据进行异步缓存
        responseCache!=nil ? [NetworkCache setHttpCache:responseObject URL:URL parameters:parameters] : nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (_isOpenLog) {PPLog(@"请求的接口：%@\n请求的参数：%@\n error = %@",URL,parameters,error);}
        if (hud.length) {[MBProgressHUD hideHUD]; }
        [[self allSessionTask] removeObject:task];
        failure ? failure(error) : nil;
    }];
    
    // 添加sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    return sessionTask;
}


#pragma mark - 上传多张图片
+ (NSURLSessionTask *)uploadImagesWithURL:(NSString *)URL
                               parameters:(id)parameters
                                     name:(NSString *)name
                                   images:(NSArray<UIImage *> *)images
                                fileNames:(NSArray<NSString *> *)fileNames
                               imageScale:(CGFloat)imageScale
                                imageType:(NSString *)imageType
                                    isHud:(NSString*)hud
                                 isWindow:(BOOL)isWindow
                                 progress:(HttpProgress)progress
                                  success:(HttpRequestSuccess)success
                                  failure:(HttpRequestFailed)failure
{
    if (hud.length) {
        if (isWindow) {
            [MBProgressHUD showActivityMessageInWindow:hud];
        }else{
            [MBProgressHUD showActivityMessageInView:hud];
        }
    }
    ///设置请求头
//    [self setValueForHTTPHeaderFieldParameters:parameters];
    
    NSURLSessionTask *sessionTask = [_sessionManager POST:URL parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSUInteger i = 0; i < images.count; i++) {
            // 图片经过等比压缩后得到的二进制文件
            NSData *imageData = UIImageJPEGRepresentation(images[i], imageScale ?: 1.f);
            // 默认图片的文件名, 若fileNames为nil就使用
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *imageFileName = NSStringFormat(@"%@%ld.%@",str,i,imageType?:@"jpg");
            
            [formData appendPartWithFileData:imageData
                                        name:name
                                    fileName:fileNames ? NSStringFormat(@"%@.%@",fileNames[i],imageType?:@"jpg") : imageFileName
                                    mimeType:NSStringFormat(@"image/%@",imageType ?: @"jpg")];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(uploadProgress) : nil;
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (_isOpenLog) {PPLog(@"请求的接口：%@\n请求的参数：%@\n responseObject = %@",URL,parameters,[self jsonToString:responseObject]);}
        if (hud.length) { [MBProgressHUD hideHUD];}

        [[self allSessionTask] removeObject:task];
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 200) {
        }else{
            NSString *msg = responseObject[@"msg"];
            if (msg.length) {
                [MBProgressHUD showTipMessageInWindow:msg];
            }
        }
        success ? success(responseObject) : nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (_isOpenLog) {PPLog(@"请求的接口：%@\n请求的参数：%@\n error = %@",URL,parameters,error);}
        if (hud.length) {[MBProgressHUD hideHUD]; }
        [[self allSessionTask] removeObject:task];
        failure ? failure(error) : nil;
    }];
    // 添加sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    return sessionTask;
}

#pragma mark - 上传文件
+ (NSURLSessionTask *)uploadFileWithURL:(NSString *)URL
                             parameters:(id)parameters
                                   name:(NSString *)name
                               filePath:(NSString *)filePath
                                  isHud:(NSString*)hud
                               isWindow:(BOOL)isWindow
                               progress:(HttpProgress)progress
                                success:(HttpRequestSuccess)success
                                failure:(HttpRequestFailed)failure
{
    if (hud.length) {
        if (isWindow) {
            [MBProgressHUD showActivityMessageInWindow:hud];
        }else{
            [MBProgressHUD showActivityMessageInView:hud];
        }
    }
    NSURLSessionTask *sessionTask = [_sessionManager POST:URL parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSError *error = nil;
        [formData appendPartWithFileURL:[NSURL URLWithString:filePath] name:name error:&error]; //  指定上传的文件
        (failure && error) ? failure(error) : nil;
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(uploadProgress) : nil;
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (_isOpenLog) {PPLog(@"请求的接口：%@\n请求的参数：%@\n responseObject = %@",URL,parameters,[self jsonToString:responseObject]);}

        if (hud.length) {
            [MBProgressHUD hideHUD];
        }
        [[self allSessionTask] removeObject:task];
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 200) {
        }else{
            NSString *msg = responseObject[@"msg"];
            if (msg.length) {
                [MBProgressHUD showTipMessageInWindow:msg];
            }
        }
        success ? success(responseObject) : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (_isOpenLog) {PPLog(@"请求的接口：%@\n请求的参数：%@\n error = %@",URL,parameters,error);}
        if (hud.length) {[MBProgressHUD hideHUD]; }
        [[self allSessionTask] removeObject:task];
        failure ? failure(error) : nil;
    }];
    // 添加sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    
    return sessionTask;
}

#pragma mark - 下载文件
+ (NSURLSessionTask *)downloadWithURL:(NSString *)URL
                              fileDir:(NSString *)fileDir
                              tailStr:(NSString *)tailStr  //添加字段 尾部拼接
                                isHud:(NSString *)hud
                             isWindow:(BOOL)isWindow
                             progress:(HttpProgress)progress
                              success:(void(^)(NSString *))success
                              failure:(HttpRequestFailed)failure {
    if (hud.length) {
        if (isWindow) {
            [MBProgressHUD showActivityMessageInWindow:hud];
        }else{
            [MBProgressHUD showActivityMessageInView:hud];
        }
    }
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]];
    __block NSURLSessionDownloadTask *downloadTask = [_sessionManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //下载进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(downloadProgress) : nil;
        });
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //拼接缓存目录
        NSString *downloadDir = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:fileDir?fileDir : @"Download"];
        //打开文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //创建Download目录
        [fileManager createDirectoryAtPath:downloadDir withIntermediateDirectories:YES attributes:nil error:nil];
        //拼接文件路径
        NSString *filePath = [downloadDir stringByAppendingPathComponent:tailStr];

//        NSString *filePath = [filePath1 stringByAppendingPathComponent:response.suggestedFilename];
//        NSLog(@"----suggestedFilename-----%@",response.suggestedFilename);
        //返回文件位置的URL路径
        return [NSURL fileURLWithPath:filePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (hud.length) {
            [MBProgressHUD hideHUD];
        }
        [[self allSessionTask] removeObject:downloadTask];
        if(failure && error) {
            failure(error) ;
            return ;
        };
        success ? success(filePath.absoluteString /** NSURL->NSString*/) : nil;
        NSLog(@"下载完成路径---%@",filePath);
    }];
    //开始下载
    [downloadTask resume];
    // 添加sessionTask到数组
    downloadTask ? [[self allSessionTask] addObject:downloadTask] : nil ;
    
    return downloadTask;
}


//json转字符串
+ (NSString *)jsonToString:(id)data {
    if(data == nil) { return nil; }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
//存储着所有的请求task数组
+ (NSMutableArray *)allSessionTask {
   if (!_allSessionTask) {
       _allSessionTask = [[NSMutableArray alloc] init];
   }
   return _allSessionTask;
}

#pragma mark - 初始化AFHTTPSessionManager相关属性
//设置请求头
+ (void)setValueForHTTPHeaderFieldParameters:(NSDictionary *)valueDic{
    //    NSArray *keyArray = [valueDic allKeys];
    //    NSArray *sortArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
    //        return [obj1 compare:obj2 options:NSNumericSearch];
    //    }];
    //    NSMutableArray*parArr = @[].mutableCopy;
    //    for (NSString *sortString in sortArray) {
    //        [parArr addObject:[NSString stringWithFormat:@"%@=%@",sortString,valueDic[sortString]]];
    //    }
    //    NSString *signStr = [parArr componentsJoinedByString:@"&"];
    //    NSString * str = [NSString stringWithFormat:@"%@%@%@",BeforePassword,signStr,AfterPassword];
    //    NSString *md5Sign = [str md5String];
    //    NSLog(@"--md5Sign---%@",md5Sign);
    //    [_sessionManager.requestSerializer setValue:md5Sign forHTTPHeaderField:kSign];
        
        
//        [_sessionManager.requestSerializer setValue:@"2g4k86f8" forHTTPHeaderField:@"appKey"];
//        [_sessionManager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"osType"];

    
    //    [_sessionManager.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"platform"];
    //    [_sessionManager.requestSerializer setValue:@"xyzx" forHTTPHeaderField:@"AppSource"];
    //    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    //    NSString * str = [userDefault objectForKey:@"token"];
    //    if (str.length>0) {
    //        [_sessionManager.requestSerializer setValue:str forHTTPHeaderField:@"Authorization"];
    //    }
}
/**
 开始监测网络状态
 */
+ (void)load {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
/**
 *  所有的HTTP请求共享一个AFHTTPSessionManager
 */
+ (void)initialize {
    _sessionManager = [AFHTTPSessionManager manager];
    //申明请求的数据是json类型
    _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    //申明返回的结果是json类型
    _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
//    响应可接受类型
    _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*",@"charset=utf-8", nil];
    // 打开状态栏的等待菊花
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    //超时时间
    _sessionManager.requestSerializer.timeoutInterval = 30.f;
//    既然有请求超时的设置，自然也有请求超时的错误，其错误码对应如下：-1001
//    [_sessionManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
//    _sessionManager.requestSerializer.timeoutInterval = 15.0f;
//    [_sessionManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
}

#pragma mark - 重置AFHTTPSessionManager相关属性
+ (void)setAFHTTPSessionManagerProperty:(void (^)(AFHTTPSessionManager *))sessionManager {
    sessionManager ? sessionManager(_sessionManager) : nil;
}

+ (void)setRequestSerializer:(RequestSerializer)requestSerializer {
    _sessionManager.requestSerializer = requestSerializer==RequestSerializerHTTP ? [AFHTTPRequestSerializer serializer] : [AFJSONRequestSerializer serializer];
}

+ (void)setResponseSerializer:(ResponseSerializer)responseSerializer {
    _sessionManager.responseSerializer = responseSerializer==ResponseSerializerHTTP ? [AFHTTPResponseSerializer serializer] : [AFJSONResponseSerializer serializer];
}

+ (void)setRequestTimeoutInterval:(NSTimeInterval)time {
    _sessionManager.requestSerializer.timeoutInterval = time;
}

+ (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field {
    [_sessionManager.requestSerializer setValue:value forHTTPHeaderField:field];
}

+ (void)openNetworkActivityIndicator:(BOOL)open {
    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:open];
}

+ (void)setSecurityPolicyWithCerPath:(NSString *)cerPath validatesDomainName:(BOOL)validatesDomainName {
    NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
    // 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    // 如果需要验证自建证书(无效证书)，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    // 是否需要验证域名，默认为YES;
    securityPolicy.validatesDomainName = validatesDomainName;
    securityPolicy.pinnedCertificates = [[NSSet alloc] initWithObjects:cerData, nil];
    
    [_sessionManager setSecurityPolicy:securityPolicy];
}


@end
